;
(function () {
    if (!Array.isArray) {
        Array.isArray = function (arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };
    }
    if (!Object.isObject) {
        Object.isObject = function (fn) {
            return typeof fn === 'object' || Object.prototype.toString.call(fn) === '[object object]';
        };
    }
    if (!Array.prototype.lastIndexOf) {
        Array.prototype.lastIndexOf = function (searchElement) {
            'use strict';
            if (this === void 0 || this === null) {
                throw new TypeError();
            }
            var n, k, t = Object(this),
                len = t.length >>> 0;
            if (len === 0) {
                return -1;
            }
            n = len - 1;
            if (arguments.length > 1) {
                n = Number(arguments[1]);
                if (n != n) {
                    n = 0;
                } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));
                }
            }
            for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {
                if (k in t && t[k] === searchElement) {
                    return k;
                }
            }
            return -1;
        };
    }
    var Track = function (channel, data) {
        this.data = data && Array.isArray(data) ? data : []
        this.channel = channel
    };
    Track.prototype.getData = function () {
        var _this = this
        return {
            channel: _this.channel,
            data: _this.data
        }
    };
    Track.prototype.error = function (error) {
        throw new Error(error)
    };
    Track.prototype.empty = function () {
        this.data = []
    };
    Track.prototype.equals = function (data, obj) {
        return (data.key == obj.key) && (data.action == obj.action);
    };
    Track.prototype.justReload = function (obj) {
        if (this.data.length <= 0) {
            return false
        }
        length = this.data.length - 1
        if (this.equals(this.data[length], obj)) {
            return true;
        }
        return false;
    };
    Track.prototype.append = function (data) {
        if (!Object.isObject(data)) {
            this.error('params is not object')
        }
        if (!data.hasOwnProperty('key') && !data['key']) {
            this.error('params key cannot be null')
        }
        if (!data.hasOwnProperty('action') && !data['action']) {
            this.error('params action cannot be null')
        }
        if (this.justReload(data)) {
            return this
        }
        var form = {
            key: data['key'],
            action: data['action'],
            timestamp: parseInt(new Date().getTime() / 1000)
        }
        this.data.push(form)
        return this
    };
    window.Track = Track
    var LocalStorageUtil = function (key) {
        this.key = key
        this.storage = window.localStorage
    };
    LocalStorageUtil.prototype.get = function () {
        var item = this.storage.getItem(this.key)
        if (!item) {
            return ''
        }
        var data = JSON.parse(item)
        var now = new Date().getTime()
        return data.expireDate > now ? data : ''
    };
    LocalStorageUtil.prototype.set = function (data, expires) {
        var now = new Date().getTime()
        expires = expires && typeof expires == 'number' ? expires : 24 * 60 * 60
        data.expireDate = now + expires * 1000
        this.storage.setItem(this.key, JSON.stringify(data))
        return this
    };
    LocalStorageUtil.prototype.remove = function () {
        this.storage.removeItem(this.key)
        return this
    };
    window.LocalStorageUtil = LocalStorageUtil;
})();
var isCallable = function (fn) {
    return typeof fn === 'function' || Object.prototype.toString.call(fn) === '[object Function]';
};

function orderTrack(channel, params) {
    var storage = new LocalStorageUtil('order_track')
    var storageData = storage.get()
    storageData = Object.isObject(storageData) && storageData.hasOwnProperty('data') ? storageData.data : ''
    var track = new Track(channel, storageData)
    var data = track.append(params).getData()
    storage.set(data, 1 * 60 * 60)
}

function orderCreateCallback(url, orderId, callback) {
    var storage = new LocalStorageUtil('order_track')
    var form = {}
    form.pathInfo = storage.get()
    form.orderId = orderId
    storage.remove();
    if (!form.pathInfo) {
        if (isCallable(callback)) {
            callback();
        }
        return '';
    }
    $.ajax({
        type: 'GET',
        url: url,
        data: form,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (res) {
            if (isCallable(callback)) {
                callback();
            }
        },
        error: function (res) {
            if (isCallable(callback)) {
                callback();
            }
        }
    });
};
(function ($) {
    var api = {
        domain: Global.apiDomain,
        getJsonp: function (method, version, data, callback) {
            var query = '?method=' + method;
            query += '&v=' + version;
            $.ajax({
                type: 'GET',
                url: api.domain + query,
                async: true,
                data: data,
                dataType: 'jsonp',
                success: function (res) {
                    (callback && typeof (callback) === "function") && callback(res);
                },
                error: function (res) {},
                complete: function () {}
            });
        }
    };
    window.api = api;

    function strCheck() {
        this.hasEmoji = function (substring) {
            for (var i = 0; i < substring.length; i++) {
                var hs = substring.charCodeAt(i);
                if (0x2100 <= hs && hs <= 0x27ff) {
                    return true;
                } else if (0x2B05 <= hs && hs <= 0x2b07) {
                    return true;
                } else if (0x2934 <= hs && hs <= 0x2935) {
                    return true;
                } else if (0x3297 <= hs && hs <= 0x3299) {
                    return true;
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                    return true;
                }
            }
            var preg = /\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g;
            if (preg.test(substring)) {
                return true;
            }
            var preg = /([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g;
            if (preg.test(substring)) {
                return true;
            }
            return false;
        }
    }
    window.strCheck = new strCheck();
    var CAKE = {};
    CAKE.cart = {
        ajax: {
            clear: function (cb) {
                $.post('/cart-empty.do', {
                    _: (new Date()).getTime()
                }, function (response) {
                    $.isFunction(cb) && cb(response);
                });
            },
            add: function (product, quantity, cb) {
                var params = {
                    "productId": product,
                    "quantity": quantity
                };
                $.post('/cart-add-goods.do', params, function (response) {
                    $.isFunction(cb) && cb(response);
                }, 'json');
            },
            update: function (indent, quantity, cb) {
                var params = {
                    "indent": indent,
                    "quantity": quantity
                };
                $.post('/cart-update-goods.do', params, function (response) {
                    $.isFunction(cb) && cb(response);
                });
            },
            remove: function (indent, cb) {
                $.post('/cart-remove.do', {
                    "object_indent": indent
                }, function (response) {
                    $.isFunction(cb) && cb(response);
                }, 'json');
            },
            total: function (cb, shipDate, shipTimeScope) {
                var params = {
                    "shipDate": shipDate,
                    "shipTimeScope": shipTimeScope || ''
                };
                $.getJSON('/cart-total.json', params, function (response) {
                    $.isFunction(cb) && cb(response);
                });
            },
            promotion: function (cb, shipDate, shipTimeScope) {
                var params = {
                    "shipDate": shipDate,
                    "shipTimeScope": shipTimeScope || ''
                };
                $.get('/cart-promotion.do', params, function (response) {
                    $.isFunction(cb) && cb(response);
                }, 'html');
            },
            amount: function (cb) {
                $.getJSON('/cart-count.do', {
                    _: Math.random()
                }, function (response) {
                    $.isFunction(cb) && cb(response);
                });
            },
            checkAddress: function (addressId, cb) {
                $.post('/address-check.do', {
                    "addressId": addressId
                }, function (response) {
                    $.isFunction(cb) && cb(response);
                }, 'json');
            }
        },
        refreshOrderPromotion: function () {
            CAKE.cart.ajax.promotion(function (response) {
                $('tr.item-order-promotion').remove();
                $('table.cart-detail tbody').append(response);
            }, $('#ship-date').val(), $('#ship-time-scop').val());
        },
        orderDetail: {},
        refreshTotal: function () {
            var params = {
                "shipDate": $('#ship-date').val(),
                "shipTimeScope": $('#ship-time-scop').val(),
                'shippingId': $('input:radio[name=shipping_id]:checked').val()
            };
            if (params.shippingId == '1') {
                params['addressId'] = $('#input-address-id').val();
            }
            $.getJSON('/cart-total.json', params, function (response) {
                var tpl = new Template('<ul> <li><span>商品金额</span><span>¥ {cost_item}</span></li> <li><span>配送费</span><span>¥ {cost_freight}</span></li> <li><span>优惠抵扣</span><span class="redco">- ¥ {pmt_amount}</span></li> <li><span>果实币抵扣</span><span class="redco">- ¥ {balance_amount}</span></li> <li><span>代金卡抵扣</span><span class="redco">- ¥ {card_amount}</span></li> </ul>');
                var order_detail = response['data']['order_detail'];
                order_detail.cost_item = parseFloat(order_detail.cost_item).toFixed(2);
                order_detail.cost_freight = parseFloat(order_detail.cost_freight).toFixed(2);
                order_detail.pmt_amount = parseFloat(order_detail.pmt_amount).toFixed(2);
                order_detail.balance_amount = parseFloat(order_detail.balance_amount).toFixed(2);
                order_detail.card_amount = parseFloat(order_detail.card_amount).toFixed(2);
                order_detail.total_amount = parseFloat(order_detail.total_amount).toFixed(2);
                $('#total-amount-detail').html(tpl.format(order_detail));
                var realTotalAmount = parseFloat(order_detail.real_total_amount);
                var $balance = $('#input-use-balance input:checkbox');
                if ($balance.prop('checked')) {
                    if (realTotalAmount < 0) {
                        alert('由于您使用了优惠券／代金卡，支付金额发生变化，请重新选择“果实币”。');
                        $.post('/cart-cancel_balance.do', {
                            _: Math.random()
                        }, function (response) {
                            $balance.prop('checked', false);
                            CAKE.cart.refreshTotal();
                        });
                    } else {
                        var cart_objects = response['data']['cart_objects'];
                        if (cart_objects.hasOwnProperty('object') && cart_objects['object'].hasOwnProperty('coupon')) {
                            var cart_coupon_objects = cart_objects['object']['coupon'];
                            if (cart_coupon_objects.length === 1) {
                                var cart_coupon_object = cart_coupon_objects[0];
                                if (cart_coupon_object.hasOwnProperty('used') && !cart_coupon_object['used']) {
                                    alert('由于您使用了"果实币"支付，不再符合优惠券使用规则，优惠券已自动取消使用');
                                    CAKE.cart.ajax.remove(cart_coupon_object['obj_ident'], function (response) {
                                        $('#action-use-coupon-btn').show();
                                        $('#block-coupon-used').hide();
                                    });
                                }
                            }
                        }
                    }
                }
                if (!$balance.prop('checked')) {
                    var $advanceTip = $('#advance-to-use');
                    var advance = parseFloat($advanceTip.data('advance'));
                    if (isNaN(advance)) {
                        advance = 0;
                    }
                    $advanceTip.html(number_format(Math.min(advance, parseFloat(order_detail.total_amount)), 2));
                }
                $('#total-amount').html('¥ ' + order_detail.total_amount);
                CAKE.cart.orderDetail = order_detail;
            });
            CAKE.cart.refreshOrderPromotion();
        },
        updateShipAddress: function (address) {
            var tpl = new Template('<input type="hidden" name="address_id" id="input-address-id" value="{addr_id}"> <h3>{name}<span>{def_addr}</span></h3> <span class="phone-number"><i></i>{mobile}</span> <span class="address"><i></i>{fullAddress}</span>');
            address['def_addr'] = (address['def_addr'] == 1 ? '默认地址' : '');
            $('#action-ship-info-block').html(tpl.format(address));
            var tpl2 = new Template('<div class="user-info">{name} <span>{mobile}</span></div> <span>{fullAddress}</span> ');
            $('#user-info-confirm').html(tpl2.format(address));
            updateShipTimeList && updateShipTimeList('#ship-date');
        },
        getMaxWord: function (weight) {
            if (weight == 1.5 || weight == 2) {
                return 16;
            } else if (weight == 3) {
                return 20;
            } else if (weight == 5) {
                return 30;
            }
            return 12;
        },
        countLength: function (words) {
            return words.replace(/[^\x00-\xff]/g, '**').length;
        }
    };
    CAKE.responseSuccess = function (response) {
        return (response.hasOwnProperty('status') && response.status == 'ok' && response.message == '');
    };
    CAKE.passport = {
        'smsVerifyCheck': '',
        'ajax': {
            checkLoginName: function (loginName, cb) {
                if (!loginName) {
                    return false;
                }
                $.post('/passport-check_login_name.do', {
                    "loginName": loginName
                }, function (response) {
                    if (response.hasOwnProperty('data')) {
                        $.isFunction(cb) && cb(response['data']['needCheckCaptcha']);
                    }
                }, 'json');
            },
            sendSMS: function (phoneNumber, verifyCode, cb) {
                $.post('/passport-send_sms.do', {
                    loginName: phoneNumber,
                    code: verifyCode
                }, function (response) {
                    if (response.hasOwnProperty('status') && response['status'] === 'ok') {
                        CAKE.passport.smsVerifyCheck = response['data']['check'];
                    }
                    $.isFunction(cb) && cb((response.hasOwnProperty('status') && response['status'] === 'ok'), response['message']);
                });
            }
        },
        checkSmsVerifyCode: function (verifyCode) {
            if (typeof VERIFY_CODE_SALT === 'string') {
                return $.md5(VERIFY_CODE_SALT + verifyCode.toLowerCase()) === CAKE.passport.smsVerifyCheck;
            }
            return true;
        },
        checkVerifyCode: function (verifyCode, verifyCheckKey) {
            verifyCheckKey = verifyCheckKey == undefined ? 'verifyCheck' : verifyCheckKey;
            if (typeof VERIFY_CODE_SALT == 'string') {
                var verifyCheck = $.cookie(verifyCheckKey);
                return $.md5(VERIFY_CODE_SALT + verifyCode.toLowerCase()) == verifyCheck;
            }
            return true;
        }
    };
    CAKE.alert = function (title, cb) {
        popUpWindow({
            title: title,
            popType: 3,
            callback: $.isFunction(cb) ? cb : $.noop()
        });
    };

    function Template(str) {
        this.str = str;
    }
    Template.prototype.format = function (arg) {
        return this.str.replace(/\{(.+?)\}/g, function (a, b) {
            return arg[b] || '';
        });
    };
    window.Template = Template;
    var Cookie = {
        options: {
            path: '/',
            domain: false,
            duration: true,
            secure: false,
            document: document,
            encode: true
        },
        write: function (key, value, options) {
            if (this.options.encode) value = encodeURIComponent(value);
            if (this.options.domain || options && options.hasOwnProperty('domain')) value += '; domain=' + options.domain;
            if (this.options.path) value += '; path=' + this.options.path;
            if (this.options.duration && options && options.hasOwnProperty('duration')) {
                var date = new Date();
                date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
                value += '; expires=' + date.toGMTString();
            }
            if (this.options.secure) value += '; secure';
            this.options.document.cookie = key + '=' + value;
        },
        read: function (key) {
            key = key.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
            var a = document.cookie.match("(?:^|;)\\s*" + key + "=([^;]*)");
            return a ? decodeURIComponent(a[1]) : null;
        },
        "delete": function (value) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = Cookie.read(value);
            if (cval != null) this.options.document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    };

    function number_format(number, decimals, decPoint, thousandsSep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number;
        var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
        var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep;
        var dec = (typeof decPoint === 'undefined') ? '.' : decPoint;
        var s = '';
        var toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + (Math.round(n * k) / k).toFixed(prec)
        };
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0')
        }
        return s.join(dec)
    };

    function getQuery(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    function isEmpty(mixedVar) {
        var undef;
        var key;
        var i;
        var len;
        var emptyValues = [undefined, null, false, 0, '', '0'];
        for (i = 0, len = emptyValues.length; i < len; i++) {
            if (mixedVar === emptyValues[i]) {
                return true;
            }
        }
        if (typeof mixedVar === 'object') {
            for (key in mixedVar) {
                if (mixedVar.hasOwnProperty(key)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    };

    function ua() {
        var u = navigator.userAgent,
            app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1,
            presto: u.indexOf('Presto') > -1,
            webKit: u.indexOf('AppleWebKit') > -1,
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
            mobile: !!u.match(/AppleWebKit.*Mobile.*/),
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
            iPhone: u.indexOf('iPhone') > -1,
            iPad: u.indexOf('iPad') > -1,
            webApp: u.indexOf('Safari') == -1,
            weixin: u.indexOf('MicroMessenger') > -1
        };
    };

    function sha1(str) {
        var hash;
        try {
            var crypto = require('crypto');
            var sha1sum = crypto.createHash('sha1');
            sha1sum.update(str);
            hash = sha1sum.digest('hex');
        } catch (e) {
            hash = undefined;
        }
        if (hash !== undefined) {
            return hash;
        }
        var _rotLeft = function (n, s) {
            var t4 = (n << s) | (n >>> (32 - s));
            return t4;
        }
        var _cvtHex = function (val) {
            var str = '';
            var i;
            var v;
            for (i = 7; i >= 0; i--) {
                v = (val >>> (i * 4)) & 0x0f;
                str += v.toString(16);
            }
            return str;
        }
        var blockstart;
        var i, j;
        var W = new Array(80);
        var H0 = 0x67452301;
        var H1 = 0xEFCDAB89;
        var H2 = 0x98BADCFE;
        var H3 = 0x10325476;
        var H4 = 0xC3D2E1F0;
        var A, B, C, D, E;
        var temp;
        str = unescape(encodeURIComponent(str));
        var strLen = str.length;
        var wordArray = [];
        for (i = 0; i < strLen - 3; i += 4) {
            j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
            wordArray.push(j);
        }
        switch (strLen % 4) {
            case 0:
                i = 0x080000000;
                break;
            case 1:
                i = str.charCodeAt(strLen - 1) << 24 | 0x0800000;
                break;
            case 2:
                i = str.charCodeAt(strLen - 2) << 24 | str.charCodeAt(strLen - 1) << 16 | 0x08000;
                break;
            case 3:
                i = str.charCodeAt(strLen - 3) << 24 | str.charCodeAt(strLen - 2) << 16 | str.charCodeAt(strLen - 1) << 8 | 0x80;
                break;
        }
        wordArray.push(i);
        while ((wordArray.length % 16) !== 14) {
            wordArray.push(0);
        }
        wordArray.push(strLen >>> 29);
        wordArray.push((strLen << 3) & 0x0ffffffff);
        for (blockstart = 0; blockstart < wordArray.length; blockstart += 16) {
            for (i = 0; i < 16; i++) {
                W[i] = wordArray[blockstart + i];
            }
            for (i = 16; i <= 79; i++) {
                W[i] = _rotLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
            }
            A = H0;
            B = H1;
            C = H2;
            D = H3;
            E = H4;
            for (i = 0; i <= 19; i++) {
                temp = (_rotLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                E = D;
                D = C;
                C = _rotLeft(B, 30);
                B = A;
                A = temp;
            }
            for (i = 20; i <= 39; i++) {
                temp = (_rotLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                E = D;
                D = C;
                C = _rotLeft(B, 30);
                B = A;
                A = temp;
            }
            for (i = 40; i <= 59; i++) {
                temp = (_rotLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                E = D;
                D = C;
                C = _rotLeft(B, 30);
                B = A;
                A = temp;
            }
            for (i = 60; i <= 79; i++) {
                temp = (_rotLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                E = D;
                D = C;
                C = _rotLeft(B, 30);
                B = A;
                A = temp;
            }
            H0 = (H0 + A) & 0x0ffffffff;
            H1 = (H1 + B) & 0x0ffffffff;
            H2 = (H2 + C) & 0x0ffffffff;
            H3 = (H3 + D) & 0x0ffffffff;
            H4 = (H4 + E) & 0x0ffffffff;
        }
        temp = _cvtHex(H0) + _cvtHex(H1) + _cvtHex(H2) + _cvtHex(H3) + _cvtHex(H4);
        return temp.toLowerCase();
    }
    window.Cookie = Cookie;
    window.CAKE = CAKE;
    window.number_format = number_format;
    window.ua = ua;
    window.getQuery = getQuery;
    window.isEmpty = isEmpty;
    window.sha1 = sha1;
})((typeof jQuery !== 'undefined' ? jQuery : Zepto));;
$(document).ready(function () {
    var fuc = {};
    fuc.init = function () {
        this.citySelect();
    };
    fuc.citySelect = function () {
        $(".app-download,.current-city,.header-user").on('mouseover', function () {
            var dataSelect = $(this).attr('data-id');
            $('#' + dataSelect).stop().slideDown(200);
            $('#' + dataSelect).siblings('.header-select').stop().slideUp(200);
        });
        $(".app-download,.current-city,.header-user").on('mouseleave', function () {
            var dataSelect = $(this).attr('data-id');
            $('#' + dataSelect).stop().slideUp(200);
        });
        $("#app-list,#current-city,#header-user,.nav-select").mouseleave(function () {
            $(this).stop().slideUp(200);
        });
        $("#app-list,#current-city,#header-user").mouseover(function () {
            $(this).stop().slideDown(200);
        });
        $('.nav-box>li').on('mouseover', function () {
            $(this).find('.nav-select').stop().slideDown(200);
        })
        $('.nav-box>li').on('mouseleave', function () {
            $(this).find('.nav-select').stop().slideUp(200);
        })
    };
    fuc.init();
});;
var popUpWindow = function (opts) {
    opts = $.extend({
        title: "确定要删除么？",
        popType: 1,
        btnLeftTxt: "取消",
        btnRightTxt: "确定",
        content: '',
        Img: '',
        closeTime: 2000,
        loginButton: '',
        popTop: 0,
        popWidth: '238px',
        removeBox: 'true',
        buttonWidth: '55px',
        cancel: function () {},
        callback: function () {}
    }, opts || {});
    var tem = '<div id="popUpWindowBox">' +
        '<i class="hideDiv"></i>' +
        '<div class="e-popUpWindowCon">' +
        '<p class="e-popUpWindowTxt"></p>' +
        '<div class="e-popUpContent"></div>' +
        '<div class="e-popUpWindowBtnBox">' +
        '<a class="e-popUpWindowBtn"></a>' +
        '<a class="e-popUpWindowBtn"></a>' +
        '</div>' +
        '</div>' +
        '</div>';
    var $popWarp, $popCon, $popTxt, $popBtn, $popBtnLeft, $popBtnRight, clTimeout$popBtnBox, $hideDiv, $popBtnBox, $popcontent;
    var init = function () {
            $("#popUpWindowBox").remove();
            $("body").append(tem);
            $popWarp = $("#popUpWindowBox");
            $popCon = $popWarp.find(".e-popUpWindowCon");
            $popTxt = $popWarp.find(".e-popUpWindowTxt");
            $popcontent = $popWarp.find(".e-popUpContent");
            $popBtnBox = $popWarp.find(".e-popUpWindowBtnBox");
            $popBtn = $popWarp.find(".e-popUpWindowBtn");
            $hideDiv = $popWarp.find(".hideDiv");
            $popBtnLeft = $popBtn.eq(0);
            $popBtnRight = $popBtn.eq(1);
            popStyle();
            operation();
            styleAdjust();
            $('.pop-img').load(function () {
                styleAdjust();
            })
        },
        popStyle = function () {
            $popCon.css({
                "width": opts.popWidth
            });
            $popBtn.css({
                "width": opts.buttonWidth
            });
            if (opts.removeBox) {
                $hideDiv.on("click", function () {
                    closePop()
                })
            }
            switch (opts.popType) {
                case 1:
                    $popBtnBox.show();
                    $popBtnLeft.on("click", closePop);
                    $popBtnRight.on("click", function () {
                        opts.callback();
                        closePop();
                    });
                    break;
                case 2:
                    $popBtnBox.hide();
                    $popcontent.hide();
                    $popTxt.css({
                        "margin-bottom": '20px'
                    });
                    clTimeout = setTimeout(closePop, opts.closeTime);
                    opts.callback();
                    break;
                case 3:
                    $popBtnLeft.hide();
                    $popcontent.hide();
                    $popTxt.css({
                        "margin-bottom": '20px'
                    });
                    $popBtnRight.width("100px").on("click", function () {
                        closePop();
                        opts.callback();
                    });
                    break;
                case 4:
                    $popBtnBox.hide();
                    weixinPop();
                    hideLogin();
                    opts.callback();
                    weixinPopStyle();
                    break;
                case 5:
                    $popBtnBox.hide();
                    loginPop();
                    hideLogin();
                    break;
                case 6:
                    $popBtnBox.hide();
                    $popCon.css({
                        'width': '750px',
                        'height': '700px',
                        'background': "url(" + Global.staticDomain + "/themes/site/img/login-tips-1220.jpg)",
                        'cursor': 'pointer'
                    })
                    $popWarp.click(function () {
                        closePop();
                        opts.callback();
                    });
                    break;
                case 8:
                    $popWarp.addClass('activity');
                    $popBtnLeft.on("click", function () {
                        opts.cancel();
                        closePop();
                    });
                    $popBtnRight.on("click", function () {
                        closePop();
                        opts.callback();
                    });
                    if (opts.Img == '') {
                        $popcontent.css('padding-top', '5px')
                    }
                    break;
            }
        },
        operation = function () {
            $popTxt.html(opts.title);
            $popcontent.html('<img class="pop-img" src="' + opts.Img + '"/>' + opts.content);
            $popBtnLeft.text(opts.btnLeftTxt);
            $popBtnRight.text(opts.btnRightTxt);
        },
        styleAdjust = function () {
            var conW = $popCon.width(),
                conH = $popCon.height();
            $popCon.css({
                "margin-left": (-1) * conW / 2 + "px",
                "margin-top": (-1) * conH / 2 - opts.popTop + "px"
            });
        };
    closePop = function () {
        $popWarp.remove();
    };
    hideLogin = function () {
        $(".hideLogin").css({
            'display': 'block',
            'height': '18px',
            'width': '18px',
            'background': "url(" + Global.staticDomain + "/themes/site/img/hide-login.png) no-repeat",
            'background-size': '100%',
            'position': "absolute",
            'top': "15px",
            'right': "10px",
        }).click(function (e) {
            closePop();
        });
    };
    weixinPop = function () {
        $popTxt.hide();
        var html = '';
        html += "<div class='weixin-box' id='login_container' style='display:none;'>";
        html += "</div>";
        html += "<a href='javascript:void(0);' class='hideLogin'></a>";
        $popCon.append(html);
        $popCon.css({
            "background": "#fff",
            "width": "388px",
            "height": "357px",
            "position": "relative",
        });
    };
    weixinPopStyle = function () {
        var weixinBox = $("#login_container");
        weixinBox.append('<span>使用微信扫码登录</span>');
        weixinBox.append('<div class="wx-renovate"></div>');
        var wxRenvate = $('.wx-renovate');
        wxRenvate.css({
            'width': '184px',
            'height': '184px',
            'background': "url(" + Global.staticDomain + "/themes/site/img/wx-renovate.png) no-repeat center,url(" + Global.staticDomain + "/themes/site/img/wx-renovate-bj.png)",
            'position': "absolute",
            'top': '70px',
            'left': '102px',
            'cursor': 'pointer',
        })
        weixinBox.css({
            'padding-top': '70px',
        }).find('img').css({
            'border': '1px solid #EFEFEF',
            'margin': '0 auto',
        });
        weixinBox.find('span').css({
            'display': 'inline-block',
            'height': '30px',
            'padding': '0 20px',
            'margin': '20px auto 0',
            'background': '#484848',
            'border-radius': '100px',
            'color': '#fff',
            'line-height': '30px',
        });
        weixinBox.show();
        wxRenvate.hide();
    };
    loginPop = function () {
        $popTxt.after("<div class='loginform'></div>");
        var loginForm = $(".loginform");
        var html = '';
        html += "<ul>";
        html += "<li><input type='text' name='wxLoginName' class='tips-login-phonename' placeholder='请输入您的手机号'/></li>";
        html += "<li class='imgtext-list'><input type='text' class='tips-login-imgtext' name='loginImgtext'   placeholder='请输入图形验证码'/><img src='/passport-verify.do' class='tips-login-img'><a href='javascript:void(0);' class='tips-login-getimgtext'></a><i></i></li>";
        html += "<li><input type='text' name='loginCodetext' class='tips-login-codetext' placeholder='请输入短信验证码'/><button class='tips-login-getcode'>获取验证码</button></li>";
        html += "<li>";
        html += "<p></p>";
        html += "</li>";
        html += "<li>";
        html += "<button id='weixin-login-submit'>验 证</button>";
        html += "</li>";
        html += "</ul>";
        html += "<a href='javascript:void(0);' class='hideLogin'></a>";
        loginForm.append(html);
        $popCon.css({
            "background": "#fff",
            "width": "388px",
            "height": "357px",
            "position": "relative",
        });
        $popTxt.css({
            "padding": "14px",
            "color": "#442818",
            "background-color": "#F3F3F1"
        });
        loginForm.find('li').css({
            'width': '302px',
            'margin-top': '10px',
            'height': '38px'
        });
        loginForm.find('li.imgtext-list').css({
            'position': 'relative',
        });
        loginForm.find('li.imgtext-list i').css({
            'position': 'absolute',
            'height': '16px',
            'width': '16px',
            'background': "url(" + Global.staticDomain + "/themes/site/img/icon.png) no-repeat",
            'background-size': '310px 120px',
            'background-position': '-61px -44px',
            'top': '12px',
            'left': '120px',
            'display': 'none',
        });
        loginForm.find('li.getcodelist ul').css({
            'height': '38px',
            'width': '604px',
            'position': 'absolute',
            'top': 0,
            'left': 0.
        });
        loginForm.find('li.getcodelist ul li').css({
            'float': 'left',
            'margin-top': 0,
        });
        loginForm.find('input').css({
            'height': '36px',
            'border': '1px solid #EFEFEF',
            'border-radius': '2px'
        });
        $(".tips-login-phonename").css({
            'width': '292px',
            'padding-left': '8px',
        });
        $(".tips-login-codetext").css({
            'width': '134px',
            'padding-left': '8px',
        });
        $(".tips-login-imgtext").css({
            'width': '130px',
            'padding-left': '8px',
        });
        $(".tips-login-img").css({
            'width': '114px',
            'height': '36px',
            'border': '1px solid #EFEFEF',
            'display': 'inline-block',
            'vertical-align': 'middle',
            'margin-left': '10px',
            'margin-top': '-2px',
        });
        $(".tips-login-getimgtext").css({
            "background": "url(" + Global.staticDomain + "/themes/site/img/weixin-login-img.png)",
            'display': 'inline-block',
            'height': '22px',
            'width': '26px',
            'vertical-align': 'middle',
            'margin-left': '8px',
        });
        loginForm.find('button').css({
            'height': '38px',
            'border-radius': '2px',
            'border': '0',
        });
        $(".tips-login-getcode").css({
            'width': '145px',
            'margin-left': '12px',
            'background': '#F5F4F3',
        });
        $("#weixin-login-submit").css({
            'width': '302px',
            'background': '#684029',
            'height': '48px',
            'color': '#fff',
            'font-size': '18px',
        }).text(opts.loginButton);
        loginForm.css({
            'width': '302px',
            'margin': '20px auto 0'
        });
        loginForm.find("p").css({
            'text-align': 'left',
            'color': '#FF714D',
        }).find('i').css({
            'display': 'inline-block',
            'vertical-align': 'middle',
            'height': '16px',
            'width': '16px',
            'margin-right': '5px',
            'background': "url(" + Global.staticDomain + "/themes/site/img/icon.png) no-repeat",
            'background-position': '-41px -44px',
            'background-size': '310px 120px',
        });
        $('a.tips-login-getimgtext').click(function (e) {
            e.preventDefault();
            $('img.tips-login-img').attr('src', '/passport-verify.do?_' + Math.random());
            $('#imgText').val('');
            return false;
        });
        $('input[name=loginImgtext]').on('keyup', function () {
            checkVerifyCode($(this));
        });
        getCodetext();
        $("#weixin-login-submit").on('click', function () {
            if (formValid()) {
                fastSubmit();
            }
        });
    };

    function checkVerifyCode(obj) {
        var loginForm = $(".loginform");
        if (obj.val().length == 4) {
            if (CAKE.passport.checkVerifyCode(obj.val().toLowerCase())) {
                loginForm.find('p').html('');
                loginForm.find('li.imgtext-list i').css({
                    'background': "url(" + Global.staticDomain + "/themes/site/img/icon.png) no-repeat",
                    'background-size': '310px 120px',
                    'background-position': '-61px -44px',
                }).show();
                return true;
            } else {
                loginForm.find('p').html('<i></i>验证码错误');
                loginForm.find('li.imgtext-list i').css({
                    'background': "url(" + Global.staticDomain + "/themes/site/img/login-pc.png) no-repeat",
                }).show();
                return false;
            }
        }
        return false;
    }
    formValid = function () {
        var loginCodetext = $(".loginform input[name=loginCodetext]");
        var loginImgtext = $(".loginform input[name=loginImgtext]");
        var loginForm = $(".loginform");
        var erroText = loginForm.find('p');
        erroText.html('');
        if (!formValidPhone()) {
            return false;
        }
        if (!checkVerifyCode(loginImgtext)) {
            erroText.html('<i></i>验证码错误');
            loginForm.find('li.imgtext-list i').css({
                'background': "url(" + Global.staticDomain + "/themes/site/img/login-pc.png) no-repeat",
            }).show();
            return false;
        }
        if (loginCodetext.val() == '') {
            erroText.html("<i></i>请填写短信验证码！");
            return false;
        }
        return true;
    };
    formValidPhone = function () {
        var loginName = $(".loginform input[name=wxLoginName]");
        var PhoneUnm = /^1\d{10}$/;
        var erroText = $(".loginform p");
        if (loginName.val() != '') {
            if (PhoneUnm.test(loginName.val())) {
                return true;
            } else {
                erroText.html("<i></i>请填写正确的手机号！");
                return false;
            }
        } else {
            erroText.html("<i></i>请填写手机号！");
            return false;
        }
    };
    getCodetext = function () {
        var getCode = $('button.tips-login-getcode');
        getCode.on('click', function () {
            if (formValidPhone()) {
                sendSms();
            }
        })
    };
    sendSms = function () {
        var erroText = $(".loginform p")
        var url = '/passport-send_sms.do';
        var code = $.trim($('.tips-login-imgtext').val());
        if ('' == code) {
            $(".loginform p").html('<i></i>' + '请输入图形验证码');
            return;
        }
        var data = {
            "loginName": $('input[name=wxLoginName]').val(),
            "code": code
        };
        $.post(url, data, function (res) {
            if (res.status != 'ok') {
                erroText.html('<i></i>' + res.message);
            } else {
                erroText.html('验证码已发送至您的手机，请查收!');
                sendCountdown();
            }
        }, 'json');
    };
    sendCountdown = function () {
        var countdown = 60;
        var getCode = $('button.tips-login-getcode')
        t = setInterval(function settime() {
            if (countdown == 0) {
                getCode.html("获取验证码");
                countdown = 60;
                clearInterval(t);
                getCode.attr('disable', true);
                $(".loginform p").html('');
            } else {
                getCode.attr('disable', false);
                getCode.html("<span>" + countdown + "秒</span>" + "后重新发送");
                getCode.find('span').css('color', '#FF714D');
                countdown--;
            }
        }, 1000);
    };
    fastSubmit = function () {
        var url = '/passport-wx-login.do';
        var data = {};
        data.phoneName = $('.loginform input[name=wxLoginName]').val();
        data.codeText = $('.loginform input[name=loginCodetext]').val();
        data.code = $('.loginform input[name=loginImgtext]').val();
        data.redirectUrl = $('input[name=redirectUrl]').val();
        $.post(url, data, function (response) {
            if (response.status == 'ok') {
                var analysisForm = {};
                analysisForm.userid = response.data.memberId;
                analysisForm.phone = data.phoneName;
                if (response.data.newMember) {
                    analysis.action('register', analysisForm);
                } else {
                    analysis.action('login', analysisForm);
                }
                var opt = {
                    "title": '登录成功!<br>系统即将跳转到登录前页面',
                    "popType": 2,
                    "callback": function () {
                        setTimeout(function () {
                            if (response.hasOwnProperty('data') && response.data.hasOwnProperty('redirectUrl')) {
                                window.location.href = response['data']['redirectUrl'];
                            } else {
                                window.location.href = '/';
                            }
                        }, 2000);
                    }
                };
                popUpWindow(opt);
                return;
            } else {
                $(".loginform p").html('<i></i>' + response.message);
                return;
            }
        }, 'json');
    };
    init();
};
if (typeof CAKE.passport.checkVerifyCode === 'undefined') {
    CAKE.passport.checkVerifyCode = function (verifyCode, verifyCheckKey) {
        verifyCheckKey = verifyCheckKey == undefined ? 'verifyCheck' : verifyCheckKey;
        if (typeof VERIFY_CODE_SALT == 'string') {
            var verifyCheck = $.cookie(verifyCheckKey);
            return $.md5(VERIFY_CODE_SALT + verifyCode.toLowerCase()) == verifyCheck;
        }
        return true;
    };
}

function weixinLogin() {
    this.reload;
    this.qrcode;
    this.oId;
    this.redirectUrl;
    this.startTime;
    this.init = function () {
        this.redirectUrl = '/';
        this.start();
        this.qrcode = new QRCode(document.getElementById("login_container"), {
            width: 182,
            height: 182
        });
    };
    this.setRedirectUrl = function (redirectUrl) {
        this.redirectUrl = redirectUrl;
    };
    this.start = function () {
        var oId = ((Math.random() * 100000000000000000000)).toString().substring(0, 10);
        var startTime = Date.parse(new Date()) / 1000;
        Cookie.write('wx_oauth_id', oId, {
            duration: 1,
            domain: '.21cake.com'
        });
        Cookie.write('wx_start_time', startTime, {
            duration: 1,
            domain: '.21cake.com'
        });
        this.oId = oId;
        this.startTime = startTime;
    };
    this.makeQrcode = function (startTime) {
        this.qrcode.makeCode(Global.apiDomain + '?method=Oauth.wxScan&id=' + this.oId + '&time=' + this.startTime);
        $('.weixin-box').find('img').attr('title', 'scan me');
    };
    this.check = function () {
        var currentTime = Date.parse(new Date()) / 1000;
        if (currentTime - this.startTime > 600) {
            $("#login_container").find('span').html('二维码已过期，请刷新重试');
            this.clearInterval();
            $('.wx-renovate').show();
            var _this = this;
            $('#login_container').find('.wx-renovate').click(function () {
                _this.start();
                _this.makeQrcode(_this.startTime);
                _this.load();
                $(this).hide();
            });
        }
    };
    this.load = function () {
        var _this = this;
        this.reload = setInterval(function () {
            _this.check();
            _this.checkLogin();
        }, 4000);
    };
    this.clearInterval = function () {
        clearInterval(this.reload);
    };
    this.checkLogin = function () {
        var form = {};
        form.id = this.oId;
        form.redirectUrl = this.redirectUrl;
        form.time = this.startTime;
        var _this = this;
        $.get('/passport-wx-login-status.do', form, function (res) {
            if (res.data.canStop) {
                _this.clearInterval();
                if (res.data.needRegist) {
                    _this.register(res.data.redirectUrl);
                } else {
                    window.location.href = res.data.redirectUrl;
                }
            }
        }, 'json');
    };
    this.register = function (redirectUrl) {
        $('.hideLogin').click();
        popUpWindow({
            title: '请完成手机绑定',
            popType: 5,
            loginButton: '验 证',
            popTop: 80,
            callback: function () {}
        });
    };
}
window.weixinLogin = weixinLogin;